package org.example.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Service
public class HeartbeatService {

    private static final Logger logger = LoggerFactory.getLogger(HeartbeatService.class);

    @Autowired
    private RedisSessionService redisSessionService;

    private static final long HEARTBEAT_TIMEOUT_MINUTES = 5; // 5分钟无心跳认为离线

    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void checkHeartbeat() {
        logger.info("开始心跳检测...");
        
        // 这里应该实现检查所有在线用户的心跳状态
        // 由于Redis中存储了用户会话信息，可以遍历检查最后心跳时间
        
        // 实际实现需要根据Redis中的数据结构来遍历检查
        // 这里简化实现，记录日志
        logger.debug("心跳检测完成");
    }

    public boolean isSessionExpired(LocalDateTime lastHeartbeatTime) {
        if (lastHeartbeatTime == null) {
            return true;
        }
        
        long minutesSinceLastHeartbeat = ChronoUnit.MINUTES.between(lastHeartbeatTime, LocalDateTime.now());
        return minutesSinceLastHeartbeat > HEARTBEAT_TIMEOUT_MINUTES;
    }
}